import base64
import json

import datetime
import requests
import urllib
import time
import hashlib
import aes


def pay_core(url, data_obj):
    data = json.dumps(data_obj)
    cipher = aes.AesEncryption(aeskey)
    data = cipher.encrypt(data)
    data = base64.urlsafe_b64encode(data).decode('utf-8')
    request_obj = {
        'merchantid': merchantid,
        'data': data,
        'timestamp': str(int(time.time()))
    }
    sign_string = secretkey + merchantid + data + request_obj['timestamp'] + secretkey
    sign = hashlib.sha256(sign_string.encode("utf-8")).hexdigest()
    request_obj['sign'] = sign
    body = urllib.parse.urlencode(request_obj)
    print(body)
    response = requests.post(url, data=request_obj)
    print(response.content)
    rsp_data = json.loads(response.content.decode('utf-8'))

    if rsp_data['message'] != 'success':
        print(response.content)
        return
    rsp_sign_string = secretkey + rsp_data['merchantid'] + rsp_data['data'] + rsp_data['timestamp'] + secretkey
    rsp_sign = hashlib.sha256(rsp_sign_string.encode('utf-8')).hexdigest()
    if rsp_sign != rsp_data['sign']:
        print("sign error")
    data = base64.urlsafe_b64decode(rsp_data['data'].encode('utf-8'))
    result = cipher.decrypt(data)
    print(result)


if __name__ == '__main__':
    merchantid = "M2018041713600452200"
    secretkey = "86B784A5412F65148F74BFF1614983CC"
    aeskey = "ED5ED08BF6EFB9F1"
    millis = int(round(time.time() * 1000))
    # url = 'https://gw.3035pay.com/pay/unionpay/c2c'
    # url = 'https://gw.3035pay.com/pay/unionpay/quicksms'
    # url = 'http://127.0.0.1:10028/ypl/quickpay'
    url = 'https://gw.3035pay.com/pay/unionpay/c2dquery'
    # now = datetime.datetime.now()
    # orderdate = now.strftime('%Y%m%d%H%M%S')
    # with open("CJ_USER_REG.txt", "r") as f:
    #     for line in f:
    time.sleep(0.2)
    # line = line.strip()
    data_obj = {
        # "ordernumber": "test" + orderdate,
        "ordernumber": "1013018042300fzo00016",
        # "payorderno": "TM201804171102420000000006114136",
        # 'amount': '50000',
        # # 'action': 1,
        # 'body': "测试",
        # "bankabbr": "ICBC",
        # "usercardno": "6226230745700219",
        # "userpid": "362201198602190014",
        # "username": "潘豪",
        # "usertel": "13418071372",
        # "cvn2": "392",
        # "expdate": "2210",
        #
        # 'settbankabbr': "CITIC",
        # "settcardno": "6226890139688526",
        # "settletel": "13418071372",
        # "settlepid": "362201198602190014",
        # "settlename": "潘豪",
        # "feerate": "2.1",
        # "settlefee": "0",
        # "smscode": "888888",
        # "backurl": "https://gw.3035pay.com/testnotify",

    }
    pay_core(url, data_obj)
    print(url)
    # rsp = requests.post(url, data= json.dumps(data_obj))
    # print(rsp.content)